<!--  -->
<template>
    <drawer
      class="import-drawer"
      direction="rtl"
      size="500px"
      :title="drawer.title"
      :drawer.sync="dialogVisible"
      :isShowMoreBtn = 'false'
      :wrapperClosable = 'true'
      containClass='contain'
      @save="saveCustomFormula"
      @cancelFun="cancelFun('import')"
      @closeDraw="cancelFun('import')"
    >
    <template slot="column" >
      <div class="main">
        <div class="left">
          <p class="formulaList">公式列表 <span @click="addCustomFormula" class="floatRight"><i style="color: #008BEE;font-size:13px" class=" V7_iconfont V7_iconV7tubiao_xinzeng-104"></i></span></p>
          <p class="formulas" :class="item._id === selectId ? 'selected' : ''" :key="item._id" @click="selectFormula(item)" v-for="item in formulaList"><span>{{item.formulaName}}</span>
            <el-popover
              placement="top"
              width="160"
              v-model="item.visible">
              <p>确定删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="item.visible = false">取消</el-button>
                <el-button type="primary" size="mini" @click="delCustomFormula(item)">确定</el-button>
              </div>
              <i slot="reference" class="V7_iconV7tubiao_shanchu fz12 V7_iconfont"></i>
            </el-popover>

          </p>
          <!-- <p class="formulas"><span>有效会话数</span><i class="V7_iconV7tubiao_shanchutong V7_iconfont"></i></p> -->
        </div>
        <div class="right">
          <div class="form">
            <el-form v-show="CustomFormulaShow" ref="myForm" label-position='top' :model="form" size="small" label-width="80px">
            <el-form-item label="公式名称" prop="formulaName" :rules="[{ required: true, message: '请输入', trigger: ['blur', 'change'] }]">
              <el-input v-model="form.formulaName"></el-input>
            </el-form-item>
            <el-form-item label="公式规则" prop="formulaStr" :rules="[{ required: true, message: '请输入', trigger: ['blur', 'change'] }]">
              <span slot="label">公式规则
                <el-tooltip class="item" effect="dark" placement="top">
                  <div slot="content">输入为了保证计算结果准确，请选择系统内已有的表头进行计算，当计算公式中涉及到'()/+-*'等计算符号时，<br>请输入英文键盘下对应的符号去进行运算帮助</div>
                  <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 myIcon" ></span>
                </el-tooltip>
                 </span>
              <el-input v-model="form.formulaStr"></el-input>
            </el-form-item>
            <el-form-item label="表头字段">
              <div class="uninput">
                {{getHeaders}}
              </div>
            </el-form-item>
            <el-form-item v-for="(item) in factors.filter(i=>i.state==='FACTOR' && !i.factor)" :prop="'variables.' + item.subString" :rules="[{ required: true, message: '请输入', trigger: ['blur', 'change'] }]" :key="'variables.' + item.subString" :label="item.subString">
              <el-select filterable  style="width:100%" @change="tochange($event, item.subString)" v-model="form.variables[item.subString]">
                <el-option
                  v-for="item in nowHeader.filter(i => !i.undisplay)"
                  :key="item.prop"
                  :label="item.label"
                  :value="item.prop">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="计算结果精度">
              <el-input-number readonly  :step="1" step-strictly style="width: 100%;text-align:left" @change="presentationFormChange(form.resultDisType)" v-model="form.digits" controls-position="right" :min="0" :max="10"></el-input-number>
            </el-form-item>
            <el-form-item label="展示形式">
              <CheckBox v-model="form.resultDisType" @change="presentationFormChange">
                <CheckBoxItem label="default">默认值</CheckBoxItem>
                <CheckBoxItem label="percentage">百分比</CheckBoxItem>
              </CheckBox>
            </el-form-item>
            <el-form-item label="计算结果">
              <el-input disabled v-model="form.calculationResults" ></el-input>
            </el-form-item>
           </el-form>
          </div>
          <div class="button">
            <el-button size="mini" type="primary" v-show="CustomFormulaShow" @click="saveCustomFormula">确定</el-button>
          </div>
        </div>
      </div>
    </template>
    </drawer>
</template>

<script lang='ts'>
import { Component, Vue, Prop, PropSync, Watch } from 'vue-property-decorator'
import drawer from '@/common/views/drawer/index.vue'
import { CheckBox, CheckBoxItem } from './index'
import * as formula from '../base/formulaUtil' // 自定义公式相关
import { commonAction } from '@/utils/common'
function unique (val, char) { // 对象数组去重
  const list = new Map()
  return val.filter(item => !list.has(item[char]) && list.set(item[char], 1))
}
@Component({ name: 'CustomFormula', components: { drawer, CheckBox, CheckBoxItem } })
export default class CustomFormula extends Vue {
  @PropSync('show', { type: Boolean }) public dialogVisible!: boolean
  @Prop({ default: () => [] }) public formulaList!: any
  @Prop({ default: '' }) public formulaType!: any
  @Prop({ default: '' }) public delUrl!: any
  @Prop({ default: () => [] }) public nowHeader!: any
  private drawer = {
    title: '配置自定义公式',
    isShow: false
  }

  private cancelFun () {
    this.dialogVisible = false
    this.$emit('cancelFun')
  }

  get getHeaders () {
    const headers = this.nowHeader.filter(i => !i.undisplay).map(item => '#' + item.label)
    return arr2string(headers)
    function arr2string (arr) {
      let result = ''
      arr.forEach(i => {
        result += i + ' '
      });
      return result
    }
  }

  private saveCustomFormula () {
    (this.$refs.myForm as any).validate(valid => {
      if (valid) {
        console.log(this.addCustomFormulaFlag)
        this.$emit('saveCustomFormula', this.form, this.addCustomFormulaFlag)
      }
    })
  }

  private CustomFormulaShow = false
  private form: any = {
    formulaName: '',
    formulaStr: '',
    digits: '',
    calculationResults: '',
    resultDisType: 'default',
    variables: {},
    formulaType: this.formulaType
  }

  public reset () {
    this.form = {
      formulaName: '',
      formulaStr: '',
      digits: '',
      calculationResults: '',
      resultDisType: 'default',
      variables: {},
      formulaType: this.formulaType
    }
    this.addCustomFormulaFlag = false
    this.CustomFormulaShow = false
    this.selectId = ''
    this.factors = [{}]
  }

  private tochange (val, key) {
    console.log(this.form)
    this.$set(this.form.variables, key, val)
  }

  private selectFormula (item) {
    this.selectId = item._id
    this.addCustomFormulaFlag = false
    this.CustomFormulaShow = true
    if (!item.variables) {
      item.variables = {}
    }
    this.$set(this, 'form', Object.assign({}, this.form, item))
  }

  private factors: any = [{}]
  private resultStorage = ''
  private addCustomFormulaFlag = false
  private selectId = ''
  private addCustomFormula () {
    if (this.addCustomFormulaFlag) {
      (this as any).$message.warning('您正在添加的公式尚未保存, 请勿重复添加')
    } else {
      this.reset()
      this.addCustomFormulaFlag = true
      this.CustomFormulaShow = true
      setTimeout(() => {
        (this.$refs.myForm as any).clearValidate()
      }, 0);
    }
  }

  private delCustomFormula (val) {
    const url = this.delUrl || '/im-report/formula/remove'
    const data = { _id: val._id }
    commonAction({ url, method: 'post', data }).then(res => {
      if (res.success) {
        (this as any).$message.success('删除成功')
        this.getCustomFormula()
        this.CustomFormulaShow = false
        this.reset()
        val.visible = false
      }
    })

    this.$emit('getCustomFormula', val)
  }

  private getCustomFormula () {
    this.$emit('getCustomFormula')
  }

  private presentationFormChange (val) {
    if (val === 'default') {
      this.form.calculationResults = Number(this.resultStorage).toFixed(this.form.digits)
    } else {
      this.form.calculationResults = this.toPercent(this.resultStorage)
    }
  }

  private toPercent (point) {
    let str = Number(point * 100).toFixed(this.form.digits)
    str += '%'
    return str
  }

  @Watch('form.formulaStr')
  private ruleChange (val) {
    try {
      if (!this.form.variables) {
        this.$set(this.form, 'variables', {})
      }
      const result = formula.parseFormulaStr(val)
      this.factors = unique(result, 'subString')?.map(item => {
        // this.$set(this.form.variables, item.subString, '')
        if (!isNaN(item.subString)) {
          item.factor = '_const'
        }
        return item
      }) || [{}]
      const xresult = formula.evalRpn(formula.dal2Rpn(result))
      if (xresult && xresult.state === 'FACTOR') {
        this.form.calculationResults = Number(1).toFixed(this.form.digits)
      } else {
        if (isNaN(xresult?.value)) {
          this.form.calculationResults = '计算有误'
        } else {
          this.form.calculationResults = Number(xresult?.value).toFixed(this.form.digits)
        }
      }
      this.resultStorage = this.form.calculationResults
    } catch (error) {
      //
    }
  }
}
</script>
<style lang='stylus' scoped>
.formulaList
  height 53px
  font-size 14px;
  font-family PingFang SC
  font-weight 400
  color #303753
  line-height 53px
  padding 0 20px
  border-bottom 1px solid #E7E9ED
/deep/.el-drawer__body>.drawer-contain.contain
  padding 0!important
  padding-bottom 20px!important
  height calc(100vh - 30px)
.main
  display flex
  height 100%
  .left
    width 36%
    height 100%
    border-right 1px solid #E7E9ED
  .right
    flex 1
    height 100%
    .form
      width 100%
      height calc(100% - 48px)
      overflow auto
      padding 20px 24px
    .button
      width 100%
      height 48px
      padding-right 24px
      padding-bottom 16px
      text-align right
.formulas
  height 40px
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  color: #303753;
  cursor pointer
  padding 0 20px
  &.selected
    color #008BEE
    font-weight: 600;
  &:hover
    background: #F3FAFF
    i
      display inline-block
  span, i
    line-height 40px

  i
    float right
    display none
    color #B3B9C7
.myIcon
  color #B3B9C7
  font-size 12px
  cursor pointer
.floatRight
  float right
  display flex
  i
    color #A6A6AE
    cursor pointer
  .slider
    display flex
    width 106px
    height 26px
    background #EFF3F8
    margin-right 18px
    border-radius 4px
    padding 2px
    justify-content: center;
    align-items: center;
    span
      display inline-block
      line-height 26px
      width 50%
      text-align center
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 600;
      color: #767E91;
    .selected
      color: #303753;
      background: #FFFFFF;
      border-radius: 4px;
.uninput
  background: #F3F6F9;
  border: 1px solid #E7E9ED;
  border-radius: 4px;
  padding 10px
</style>
